﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CreateAMultisessionDisc
{

  // This script adds data files from a single directory tree to a
  // disc (a new session is added, if the disc already contains data)

  // Copyright (C) Microsoft Corporation. All rights reserved.



  class Program
  {

    // *** CD/DVD disc file system types
    public const int FsiFileSystemISO9660 = 1;
    public const int FsiFileSystemJoliet = 2;
    public const int FsiFileSystemUDF102 = 4;

    static int Main(string[] args)
    {


      dynamic Index;                // Index to recording drive.
      dynamic Recorder;             // Recorder object
      dynamic Path;                 // Directory of files to add
      dynamic Stream;               // Data stream for burning device

      Index = 0;                // First drive on the system
      Path = @"G:\BurnDir";      // Files to add to the disc

      // Create a DiscMaster2 object to connect to optical drives.
      dynamic DiscMaster;
      DiscMaster = new IMAPI2.MsftDiscMaster2();

      // Create a DiscRecorder2 object for the specified burning device.
      dynamic UniqueId;
      Recorder = new IMAPI2.MsftDiscRecorder2();
      UniqueId = DiscMaster.Item(Index);
      Recorder.InitializeDiscRecorder(UniqueId);

      // Create a DiscFormat2Data object and set the recorder
      dynamic DataWriter;
      DataWriter = new IMAPI2.MsftDiscFormat2Data();
      DataWriter.Recorder = Recorder;
      DataWriter.ClientName = "IMAPIv2 TEST";

      // Create a new file system image object
      dynamic FSI;
      FSI = new IMAPI2FS.MsftFileSystemImage();

      // Import the last session, if the disc is not empty, or initialize
      // the file system, if the disc is empty
      if (!DataWriter.MediaHeuristicallyBlank)
      {
        try
        {
          FSI.MultisessionInterfaces = DataWriter.MultisessionInterfaces;
        }
        catch (Exception ex)
        {
          Console.WriteLine("Multisession is not supported for this disc");
          return 1;
        }
        Console.WriteLine("Importing data from the previous session...");
        FSI.ImportFileSystem();
      }
      else
      {
        FSI.ChooseImageDefaults(Recorder);
      }

      // Add the directory and its contents to the file system 
      Console.WriteLine("Adding " + Path + " directory to the disc...");
      FSI.Root.AddTree(Path, false);

      // Create an image from the file system image object
      dynamic Result;
      Result = FSI.CreateResultImage();
      Stream = Result.ImageStream;

      // Write stream to disc using the specified recorder
      Console.WriteLine("Writing content to the disc...");
      DataWriter.Write(Stream);

      Console.WriteLine("Finished writing content.");

      return 0;

    }
  }
}